package com.jiyi.activity.leader;

import android.app.Dialog;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jiyi.adapter.DividerItemDecoration;
import com.jiyi.adapter.recyclerview.CommonAdapter;
import com.jiyi.adapter.recyclerview.base.ViewHolder;
import com.jiyi.adapter.recyclerview.wrapper.EmptyWrapper;
import com.jiyi.bean.main.NewsListJson.NewsBean;
import com.jiyi.bean.maintenance.Task;
import com.jiyi.common.StringInterface;
import com.jiyi.common.VolleyRequest;
import com.jiyi.easemob.util.UserHelp;
import com.jiyi.inteface.OnRcvScrollListener;
import com.jiyi.inteface.WebApi;
import com.swift.maintenance.R;
import com.swift.maintenance.base.AppBase;
import com.swift.maintenance.base.AppConfig;
import com.swift.maintenance.utils.ToastUtil;
import com.swift.maintenance.utils.UserInfoUtil;
import com.swift.utils.DialogTool;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

public class WbWorkStatisticsFragment extends Fragment {

	List<NewsBean> newsList = new ArrayList<NewsBean>();
	LayoutInflater inflater;
	@BindView(R.id.id_stickynavlayout_innerscrollview)
	RecyclerView mListView;
	private List<Task> mTasks = new ArrayList<Task>();
	EmptyWrapper adapter;
	ViewGroup container;
	int type;

	Dialog dialog;

	// 是否刷新模式
	boolean isRefresh = false;
	int pageNo = 1;// 页码
	private final int LOAD_DATA = 5; // 加载数据事件
	private boolean loadfinish = true; // 指示数据是否加载完成
	// 月份，用户id
	String mouth, id;

	@Override
	public View onCreateView(LayoutInflater inflater,
			@Nullable ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_tab, null, false);
		ButterKnife.bind(this, view);
		this.inflater = inflater;
		this.container = container;
		init();
		return view;
	}

	@Override
	public void onDestroyView() {
		DialogTool.hideDialog(dialog);
		super.onDestroyView();
	}

	private void init() {
		getIntentData();
		onRefresh();
		setAdapter();
	}

	/**
	 * @author: HYM
	 * @Title: getIntentData
	 * @Description: TODO(这里用一句话描述这个方法的作用) void
	 * @date: 2017-8-30
	 */
	private void getIntentData() {
		mouth = getArguments().getString("mouth");
		id = getArguments().getString("id");
	}

	private void getData() {

		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN,
				UserInfoUtil.getCurrentUserAccessToken());
		params.put("p", pageNo + "");
		params.put("month", mouth);
		params.put("id", id);

		VolleyRequest.StringRequestPost(getContext(),
				WebApi.MAINTENANCE_LEADER_WORK_DETAIL_WB_LIST, "", params,
				new StringInterface(getContext()) {

					@Override
					public void stringSuccess(String result) {
						try {
							JSONObject obj = new JSONObject(result);
							String status = obj.getString("status");
							String info = obj.getString("info");
							if (status.equals("200")) {
								String data = obj.getString("data");
								List<Task> tasks = new Gson().fromJson(data,
										new TypeToken<List<Task>>() {
										}.getType());

								if (isRefresh) {
									mTasks.clear();
								}

								if (tasks.size() > 0) {
									mTasks.addAll(tasks);
									pageNo++;
								} else {

								}

								// mTasks.clear();
								// mTasks.addAll(tasks);
								adapter.notifyDataSetChanged();
								loadfinish = true; // 加载完成
							} else if (status.equals("404")
									&& info.contains("尚未登录")) {
								ToastUtil.getInstances().showMsg(
										"尚未登录或该用户在其他地方登录，请重新登录！");
								// 清除环信登录
								UserHelp.getInstance().clearUser(
										AppBase.Context, true);
								return;
							} else {
								ToastUtil.getInstances().showMsg(info);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						} finally {
						}
					}

					@Override
					public void stringError(VolleyError error) {
						ToastUtil.getInstances().showMsg(
								R.string.err_http_response);
					}
				});
	}

	private void setAdapter() {
		mListView.setLayoutManager(new LinearLayoutManager(getContext()));
		mListView.addItemDecoration(new DividerItemDecoration(getContext(),
				DividerItemDecoration.VERTICAL_LIST, getResources()
						.getDrawable(R.drawable.drvice_10)));

		// 初始化适配器
		CommonAdapter mCommonAdapter = new CommonAdapter<Task>(getContext(),
				R.layout.item_maintenance_work_statis, mTasks) {
			@Override
			protected void convert(final ViewHolder holder, final Task task,
					final int position) {
				holder.setText(R.id.tvCompany, task.getTask_name());
				holder.setText(R.id.tvDate, task.getTask_time());
				holder.setText(R.id.tvInfo, task.getParticipants());
				holder.setText(R.id.tvUsername, task.getUser_name());
//				0：待接收的新任务（这里不会出现），1：代签到，2：待抽检，3：已完成
				if (task.getStatus() == 1) {
					holder.setText(R.id.tvDesc, "待签到");
				}
				else if (task.getStatus() == 2) {
					holder.setText(R.id.tvDesc, "待抽检");
				}
				else if (task.getStatus() == 3) {
					holder.setText(R.id.tvDesc, "已完成");
				}
				else {
					holder.setText(R.id.tvDesc, "待接收");
				}
			}
		};

		adapter = new EmptyWrapper(mCommonAdapter);

		View emptyView = inflater.inflate(R.layout.empty_view_text_and_image,
				container, false);
		ImageView ivEmptyTip = (ImageView) emptyView
				.findViewById(R.id.ivEmptyTip);
		TextView tvEmptyTip = (TextView) emptyView
				.findViewById(R.id.tvEmptyTip);
		ivEmptyTip.setImageResource(R.mipmap.tip_empty_huodong);
		tvEmptyTip.setText(R.string.NO_DATA);
		adapter.setEmptyView(emptyView);

		mListView.setAdapter(adapter);
		adapter.notifyDataSetChanged();
		mListView.addOnScrollListener(new OnRcvScrollListener() {
			@Override
			public void onBottom() {
				super.onBottom();
				if (loadfinish) {
					Log.e("加载到底部 pageNo = ", pageNo + "");
					loadMore();
				}

			}
		});
	}

	public void onRefresh() {
		isRefresh = true;
		pageNo = 1;
		mHandler.sendEmptyMessage(LOAD_DATA);
	}

	/**
	 * 处理中心
	 */
	Handler mHandler = new Handler() {
		public void dispatchMessage(android.os.Message msg) {
			switch (msg.what) {
			case LOAD_DATA:
				if (loadfinish) {
					loadfinish = false;
					getData();
				}
				break;
			default:
				break;
			}
		};
	};

	/**
	 * 作者：hym 日期：2017-4-6 描述：加载更多数据
	 */
	void loadMore() {
		isRefresh = false;
		mHandler.sendEmptyMessage(LOAD_DATA);
	}

	
}
